package com.ruslan.magaz.service;

import java.util.List;





import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import com.ruslan.magaz.entity.Info;
import com.ruslan.magaz.entity.InfoName;
import com.ruslan.magaz.entity.User;
import com.ruslan.magaz.repository.InfoRepository;
import com.ruslan.magaz.repository.UserRepository;

@Service("infoService")
public class InfoServiceImpl implements InfoService {

	@Autowired
	private UserRepository userRepository;
	@Autowired
	private InfoRepository infoRepository;
	
	@Override
	public void addInfo(Info info) {
		infoRepository.saveAndFlush(info);
		
	}

	@Override
	public void removeInfo(int id) {
		infoRepository.delete(id);
        infoRepository.flush();
		
	}

	@Override
	public Info getInfoById(int id) {
		return infoRepository.findOne(id);
	}

	@Override
	public Page<Info> getInfosByUser(int userId, int page, Integer maxResults) {
		User user = userRepository.findOne(userId);

        if (user != null) {
            PageRequest request = new PageRequest(page, maxResults, Sort.Direction.ASC, "infoName.id");
            return infoRepository.findAllByUser(user, request);

        } else {
            return null;
        }
	}

	@Override
	public List<InfoName> getInfoNames() {
        return infoRepository.findAllInfoNames();
	}

	@Override
	public Info updateInfo(Info info) {
		return infoRepository.saveAndFlush(info);
	}

	@Override
	public InfoName getInfoNameById(int id) {
		return infoRepository.findOneInfoName(id);
	}

	@Override
	public int countSameInfo(InfoName infoName, String value) {
		return infoRepository.countSameInfo(infoName, value);
	}

	@Override
	public int countInfosForUser(User user) {
		return infoRepository.countInfosForUser(user);
	}

	@Override
	public int countIdenticalInfo(int id, InfoName infoName, String value) {
		return infoRepository.countIdenticalInfo(id,infoName,value);
	}
	
}
